﻿# -*- coding:utf-8 -*-
#
# склад
#
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model


class Command( NoArgsCommand ):

    help = 'Import department from Sklad app to SHM  app.'
    requires_model_validation = True
    
    def handle_noargs(self, **options):
        from django.db.models import get_models
        log = []
        skiped = 0
        affected = 0 
         
        DepartmentSklad = get_model('sklad', 'Departmentex')
        DepartmentShm = get_model('shm', 'Department')
        Employee = get_model('shm', 'Employee')
        Phone = get_model('shm', 'Phone')
       
        departmentsklad = DepartmentSklad.objects.all()
        for item in departmentsklad:
            '''
            Sklad
            class Department(models.Model): Sklad
                name = models.CharField(max_length=192, blank=True, verbose_name="Наименование")
                boss = models.CharField(max_length=192, blank=True, verbose_name="Руководитель")
                phone = models.CharField(max_length=48, blank=True, verbose_name="Телефон")
                data = models.DateTimeField(null=True, blank=True, verbose_name="Дата")
                user = models.ForeignKey(User, verbose_name="Пользователь")
            '''
            '''
            SHM
            class Department(models.Model):
                parent = models.ForeignKey("self", blank=True, null=True, verbose_name="Головной отдел")
                level = models.IntegerField(blank=True, default=1, verbose_name="уровень")
                name = models.CharField(max_length=64, verbose_name="Наименование")
                room = models.CharField(max_length=8, blank=True, verbose_name="Комната")
                phone = models.ManyToManyField(Phone, blank=True, null=True, verbose_name="Телефон")
                
            class Phone(models.Model):
                number = models.CharField(max_length=64, verbose_name="Номер")
                type = models.CharField(max_length=16, blank=True, verbose_name="Тип")
                room = models.CharField(max_length=8, blank=True, verbose_name="Комната")     
                
            class Employee (models.Model):
                department = models.ForeignKey(Department)
                name1 = models.CharField(max_length=64, verbose_name="Фамилия")
                name2 = models.CharField(max_length=64, blank=True, verbose_name="Имя")
                name3 = models.CharField(max_length=64, blank=True, verbose_name="Отчество")
                post = models.CharField(max_length=64, blank=True, verbose_name="Должность")
                ktit_staff = models.BooleanField(verbose_name="Сотрудник КТиТ")
                boss = models.BooleanField(verbose_name="Руководитель")
                phone = models.ManyToManyField(Phone, blank=True, null=True, verbose_name="Телефон")       
                
            '''
            # Выполнение всех операций в одной транзакции
            from django.db import transaction
            transaction.enter_transaction_management()
            try:
                transaction.managed(True)
                #
                phone = Phone(number=item.phone)
                phone.save()
                
                departmentshm = DepartmentShm(id=item.id, parent=None, name=item.name)
                departmentshm.save()
                departmentshm.phone.add(phone)
                departmentshm.save()
                
                employee = Employee(department = departmentshm, name1=item.boss, boss=True)
                employee.save()
                employee.phone.add(phone)
                employee.save()
                #
                transaction.commit()
            finally:
                transaction.rollback()
                transaction.leave_transaction_management()            
          
        #print 'Part skiped ( never register in waybill ) - %s' % skiped
        #print 'Part affected - %s' % affected        
        #print 'Part all - %s' %  (affected + skiped )
        
        log.append(u'Job done...')
        return "\n".join( log )
        
        
        
        